package com.wetao.education.module_reader.activity;


import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.reflect.TypeToken;
import com.wetao.education.module_reader.R;
import com.wetao.education.module_reader.contract.ReadPushDetailCon;
import com.wetao.education.module_reader.presenter.ReadPushDetailPre;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.response.GetSubjectList;
import com.wetao.lib_common.bean.response.ReadPushFirstInfo;
import com.wetao.lib_common.bean.response.ReadPushListInfo;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.ReadPushRecord;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.DownloadUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.GsonUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.view.SuperFileView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


/**
 * 文档阅读界面
 */

@Route(path = ConstantArouter.PATH_READER_READPUSHDETAILACTIVITY)
public class ReadPushDetailActivity extends BaseActivity<ReadPushDetailCon.View, ReadPushDetailPre> implements
        ReadPushDetailCon.View, View.OnClickListener {


    private static final String TAG = "ReadPushDetailActivity";

    @Autowired
    String title;
    @Autowired
    int state;  // 2已读  3 未读
    @Autowired
    String records;
    @Autowired
    String readPushItem;

    private String fileUrl;
    private boolean isLoadComplete = false;
    private ReadPushFirstInfo.DataBean curBean;

    private SuperFileView superFileView;
    private LinearLayout ll_bottom;
    private TextView tv_finish;
    private TextView tv_finish_and_next;


    private List<ReadPushListInfo.Data.RecordsBean> recordsBeans;
    private LinkedList<ReadPushListInfo.Data.RecordsBean> notReadList = new LinkedList<>();

    private long startReadTime = 0;


    @Override
    public int getLayoutId() {
        return R.layout.reader_push_detail;
    }

    @Override
    public ReadPushDetailPre createPresenter() {
        return new ReadPushDetailPre(this);
    }

    @Override
    public ReadPushDetailCon.View createView() {
        return this;
    }

    @Override
    public void init() {
        initView();
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }


    private void initView() {

        initTitleLayout();
        setTvTitle(title, true);
        initData();
        ll_bottom = findViewById(R.id.ll_read_bottom);
        tv_finish = findViewById(R.id.tv_finish_read);
        tv_finish_and_next = findViewById(R.id.tv_next_reader);
        superFileView = findViewById(R.id.mSuperFileView);

        initFileView();
        showViewVisible();

        iv_back.setOnClickListener(this);
        tv_finish.setOnClickListener(this);
        tv_finish_and_next.setOnClickListener(this);


//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            //判断是否可以写入数据到系统
//            if (!Settings.System.canWrite(this)) {
//                Intent i = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
//                i.setData(Uri.parse("package:" + this.getPackageName()));
//                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(i);
//            }
//        }
    }

    private void initFileView(){
        superFileView.setOnGetFilePathListener(new SuperFileView.OnGetFilePathListener() {
            @Override
            public void onGetFilePath(SuperFileView mSuperFileView2) {
                showLoadingDialog();
                getFilePathAndShowFile(mSuperFileView2);
            }

            @Override
            public void onLoadComplete() {
                startReadTime = System.currentTimeMillis();
                setLoadComplete(true);
                beginReadReq();
                hideLoadingDialog();
            }

            @Override
            public void onLoadError() {
                hideLoadingDialog();
                ToastUtil.initToast("抱歉,该文件无法打开~");
            }
        });

        superFileView.show();
    }


    private void initData(){
        if (readPushItem!=null){
            curBean = JsonUtils.fromJson(readPushItem, ReadPushFirstInfo.DataBean.class);
            if (curBean!=null){
                setFilePath(curBean.getPdfUrl()==null?curBean.getFileUrl():curBean.getPdfUrl());
            }
        }

        if (records != null) {
            recordsBeans = JsonUtils.fromJsonList(records,
                    new TypeToken<List<ReadPushListInfo.Data.RecordsBean>>(){}.getType());
            if (recordsBeans!=null){
                for (int i = recordsBeans.size() - 1; i >=0;i--){
                    ReadPushListInfo.Data.RecordsBean bean = recordsBeans.get(i);
                    if (bean.getReadStatus()== 3 && !bean.getFileUrl().equals(curBean.getFileUrl())){ //未读
                        notReadList.add(recordsBeans.get(i));
                    }
                }
            }
        }
    }

    public void showLoadingDialog() {
        DialogXUtil.waitDialogShow("正在加载...");
    }

    public void hideLoadingDialog() {
        DialogXUtil.waitDialogDismiss();
    }

    /**
     * 开始阅读
     */
    private void beginReadReq() {
        getPresenter().beginRead(ComUtil.getHashmapByStr(
                new String[]{"readPushId"}, new String[]{curBean.getReadPushId().toString()}), false, false);
    }

    /**
     * 完成阅读
     */
    private void endReadReq(int readTime,boolean isExit) {
        getPresenter().endRead(ComUtil.getHashmapByStr(
                new String[]{"readPushId","readTime"}, new String[]{curBean.getReadPushId().toString(), String.valueOf(readTime)}),
                false, false,isExit);
    }

    /**
     * 获取最早的数据
     */
    private void getFirstReadReq() {
        getPresenter().getFirstRead(false,false);
    }


    /**
     * 获取路径并打开
     *
     * @param mSuperFileView2
     */
    private void getFilePathAndShowFile(SuperFileView mSuperFileView2) {

        File cacheFile = FileUtils.getPdfCacheFile(getFilePath());
        if (cacheFile.exists()){
            mSuperFileView2.displayFile(cacheFile);
        }else if (getFilePath().contains("http")){
            downLoadFromNet(getFilePath(), mSuperFileView2);
        }
    }

    private void downLoadFromNet(final String url, final SuperFileView mSuperFileView) {

        //1.网络下载、存储路径、
        File cacheFile = FileUtils.getPdfCacheFile(url);
        if (cacheFile.exists()) {
            if (cacheFile.length() <= 0) {
                LogUtils.d("删除空文件！！");
                cacheFile.delete();
                return;
            }
        }

        File dir = FileUtils.getPDFFolder();
        DownloadUtil.get().download(this, url,dir.getAbsolutePath(), new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(final String path) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.e("下载文件成功");
                        mSuperFileView.displayFile(new File(path));
                    }
                });
            }

            @Override
            public void onDownloading(final int sum, final int total, final int progress) {

            }

            @Override
            public void onDownloadFailed() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideLoadingDialog();
                        ToastUtil.initToast("抱歉,文件加载失败~");
                        LogUtils.e("下载文件失败");
                    }
                });
            }

            @Override
            public void onNetwork(boolean isNetwork) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideLoadingDialog();
                        ToastUtil.initToast("抱歉,文件加载失败~");
                        LogUtils.e("下载文件成功-网络连接断开");
                        File file = FileUtils.getPdfCacheFile(url);
                        if (!file.exists()) {
                            LogUtils.d("删除下载失败文件");
                            file.delete();
                        }
                    }
                });
            }
        });
    }


    public String getFilePath() {
        return fileUrl;
    }

    public void setFilePath(String filePath) {
        this.fileUrl = filePath;
    }


    public boolean isLoadComplete() {
        return isLoadComplete;
    }

    public void setLoadComplete(boolean loadComplete) {
        isLoadComplete = loadComplete;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (superFileView != null) {
            superFileView.onStopDisplay();
        }
    }


    /**
     * 删除本地文档
     */
    private void deleteLocalFile() {
        File dir = FileUtils.getPDFFolder();
        if (dir.exists()){
            for (File f : dir.listFiles()){
                f.delete();
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //未完成阅读，将阅读数据入库
            if (curBean.getReadStatus() == 3){
                insertReadPushRecord();
            }
            finish();
        } else if (id == R.id.tv_finish_read) {
            //加载完文档才能点击
            if (isLoadComplete()){
                showFinishReadDialog(false);
            }
        } else if (id == R.id.tv_next_reader) {
            if (isLoadComplete()){
                showFinishReadDialog(true);
            }

        }
    }

    /**
     * 未完成阅读则保存数据库
     */
    private void insertReadPushRecord() {
        //先判断是否阅读过，阅读过则时间累加
        ReadPushRecord item = DBUtils.getInstance(this).getReadPushRecordById(curBean.getReadPushId());
        int readTime = 0;
        if (startReadTime != 0){
            readTime = (int) ((System.currentTimeMillis() - startReadTime)/1000);
        }
        if (item == null){
            item = new ReadPushRecord(null,
                    curBean.getReadPushId(), curBean.getReadPushTitle(),curBean.getPushTime(),curBean.getFileUrl(),
                    curBean.getSubjectName(),readTime,curBean.getReadStatus(),new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
            DBUtils.getInstance(this).insertReadPushRecord(item);
        }else{
            readTime = item.getReadTime() + readTime;
            item.setReadTime(item.getReadTime() + readTime);
            DBUtils.getInstance(this).updateReadPushRecord(item);
        }
        LogUtils.i("m1: finish readTime=" + readTime);
    }

    /**
     * 完成阅读并打开下一篇
     */
    private void finishAndOpenNewFile() {
        if (notReadList.size() > 0){
            notReadList.removeFirst();
        }
        showViewVisible();
        superFileView.onStopDisplay();
        superFileView.SwitchFileView();
        superFileView.show();
    }


    /**
     * 完成提示弹框
     * @param finishAndNext
     */
    private void showFinishReadDialog(final boolean finishAndNext) {
        String content = "";
        if (finishAndNext){
            content = getString(R.string.read_finish_and_next_dialog_content);
        }else{
            content = getString(R.string.read_finish_read_dialog_content);
        }
        DialogXUtil.customDialogShow(content, new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {
                //计算结束时间
                int readTime = 0;
                ReadPushRecord item = DBUtils.getInstance(ReadPushDetailActivity.this).getReadPushRecordById(curBean.getReadPushId());
                if (item != null){
                    readTime += item.getReadTime();
                }
                readTime += (int) ((System.currentTimeMillis() - startReadTime)/1000);
                endReadReq(readTime,!finishAndNext);
                if (!finishAndNext){
                    deleteLocalFile();
                }
            }

            @Override
            public void onListenDialogCancel() {

            }

            @Override
            public void onListenDialogClose() {

            }
        });
    }


    @Override
    public void beginReadResult(BaseResponse response) {

    }

    @Override
    public void beginReadFail() {

    }

    @Override
    public void endReadResult(BaseResponse response,boolean isExit) {
        LogUtils.i("m1 endReadResult start");
        exit(isExit);
        if (!isExit){
            setLoadComplete(false);
            getFirstReadReq();
        }
    }

    @Override
    public void endReadFail(boolean isExit) {
        LogUtils.i("m1 endReadFail start");
        exit(isExit);
    }

    @Override
    public void getFirstReadResult(ReadPushFirstInfo response) {
        if (response.getData()!=null){
            curBean = response.getData();
            setFilePath(curBean.getPdfUrl()==null?curBean.getFileUrl():curBean.getPdfUrl());
            setTvTitle(curBean.getReadPushTitle(),true);
            finishAndOpenNewFile();
        }
    }

    @Override
    public void getFirstReadFail() {
        ToastUtil.initToast("抱歉,下一篇加载失败~");
    }

    /**
     * 是否显示完成阅读视图
     */
    private void showViewVisible(){
        if (state == 2) {
            ll_bottom.setVisibility(View.GONE);
        } else {
            ll_bottom.setVisibility(View.VISIBLE);
        }

        if (notReadList.size() == 0){
            tv_finish_and_next.setVisibility(View.GONE);
        }else {
            tv_finish_and_next.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 是否退出
     * @param isExit
     */
    private void exit(boolean isExit){
        if (isExit){
            finish();
        }
    }
}
